package com.ruoyi.menu.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.menu.entity.TbMenu;
import com.ruoyi.menu.service.MenuService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {

    @Autowired
    private MenuService tbMenuService;
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 新增菜品
     */
    @RequiresPermissions("menu:menu:add")
    @Log(title = "菜品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbMenu tbMenu)
    {
        return toAjax(tbMenuService.insertTbMenu(tbMenu));
    }


    /**
     * 修改菜品
     */
    @RequiresPermissions("menu:menu:edit")
    @Log(title = "菜品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbMenu tbMenu)
    {
        return toAjax(tbMenuService.updateTbMenu(tbMenu));
    }

    /**
     * 获取菜品详细信息
     */
    @RequiresPermissions("menu:menu:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tbMenuService.selectTbMenuById(id));
    }

    /**
     * 查询菜品列表
     */
    @RequiresPermissions("menu:menu:list")
    @GetMapping("/list")
    public TableDataInfo list(TbMenu tbMenu)
    {
        startPage();
        List<TbMenu> list = tbMenuService.selectTbMenuList(tbMenu);
        return getDataTable(list);
    }

    /**
     * 删除菜品
     */
    @RequiresPermissions("menu:menu:remove")
    @Log(title = "菜品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tbMenuService.deleteTbMenuByIds(ids));
    }


    @RequiresPermissions("menu:menu:export")
    @Log(title = "菜品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void download(HttpServletResponse response) throws IOException {
        TbMenu tbMenu = new TbMenu();
        List<TbMenu> list = tbMenuService.selectTbMenuList(tbMenu);
        ExcelUtil<TbMenu> util = new ExcelUtil<TbMenu>(TbMenu.class);
        util.exportExcel(response, list, "菜品数据");
    }

    @PostMapping("/import")
    public AjaxResult importExcel(@RequestParam(value = "file") MultipartFile file) throws Exception {
        System.out.println("线程1"+Thread.currentThread().getName());

            tbMenuService.importExcel(file);


        return AjaxResult.success("我们使用多线程正在后台导入，请您稍后刷新");
    }

    /**
     * 用户点餐加入购物车方法
     * @param tbMenu
     * @return
     */
    @PostMapping("myshoppingcart")
    public AjaxResult MyshoppingCart(@RequestBody TbMenu tbMenu,
                                     @RequestParam String tableId,
                                    @RequestParam String userId){
        LoginUser loginUser = com.ruoyi.common.security.utils.SecurityUtils.getLoginUser();
        Integer merchantId = Math.toIntExact(loginUser.getUserid());
        //记录当前用户的桌号
        redisTemplate.opsForValue().set(merchantId+"table",tableId);
        redisTemplate.opsForValue().set(merchantId+"merchant",userId);
        //记录总价格
        BigDecimal amountRedis = (BigDecimal) redisTemplate.opsForValue().get(merchantId + "amount");

        if(amountRedis!=null){
            BigDecimal menuPrice = tbMenu.getMenuPrice();
            BigDecimal amount = menuPrice.add(amountRedis);
            redisTemplate.opsForValue().set(merchantId+"amount",amount);
        }else{
            BigDecimal menuPrice = tbMenu.getMenuPrice();
            BigDecimal amount = menuPrice;
            redisTemplate.opsForValue().set(merchantId+"amount",amount);
        }
        //合并购物车
        TbMenu tbMenuRedis = (TbMenu) redisTemplate.opsForHash().get("cart" + merchantId, tbMenu.getId().toString());
        if(tbMenuRedis!=null){
            tbMenu.setMenuCount(tbMenuRedis.getMenuCount()+tbMenu.getMenuCount());
        }
        redisTemplate.opsForHash().put("cart"+merchantId,tbMenu.getId().toString(),tbMenu);
            return new AjaxResult(1,"添加购物车成功");

    }



    /**
     * 用户点餐加入购物车方法
     * @param tbMenu
     * @return
     */
    @PostMapping("addCard")
    public AjaxResult addCard(@RequestBody TbMenu tbMenu){
        //获取用户id
        LoginUser loginUser = com.ruoyi.common.security.utils.SecurityUtils.getLoginUser();
        Integer merchantId = Math.toIntExact(loginUser.getUserid());
        //合并购物车
        TbMenu tbMenuRedis = (TbMenu) redisTemplate.opsForHash().get("cart:" + merchantId, tbMenu.getId().toString());
        if(tbMenuRedis!=null){
            tbMenu.setMenuCount(tbMenuRedis.getMenuCount()+tbMenu.getMenuCount());
        }
           //添加到购物车
        redisTemplate.opsForHash().put("cart:"+merchantId,tbMenu.getId().toString(),tbMenu);
        List values = redisTemplate.opsForHash().values("cart:" + merchantId);
        Set keys = redisTemplate.opsForHash().keys("cart:" + merchantId);
        return new AjaxResult(1,"添加购物车成功");

    }

    //购物车列表
    @GetMapping("cartList")
    public List<TbMenu> cartList(){
        //获取用户id
        LoginUser loginUser = com.ruoyi.common.security.utils.SecurityUtils.getLoginUser();
        Integer merchantId = Math.toIntExact(loginUser.getUserid());
        List values = redisTemplate.opsForHash().values("cart:" + merchantId);
            return values;
    }


    /**
     *  id查询菜品对象 修改库存
     */
    @GetMapping(value = "findByIdmenu")
    public TbMenu findByIdmenu(@RequestParam("id") Long id)
    {
        return tbMenuService.selectTbMenuById(id);
    }

    //修改库存数量

    /**
     * 修改菜品
     */
    @PostMapping("updatemenu")
    public AjaxResult updatemenu(@RequestBody TbMenu tbMenu)
    {
        return toAjax(tbMenuService.updateTbMenu(tbMenu));
    }





}
